using UnityEngine;

public class Chest : MonoBehaviour
{
    public LootSystem lootSystem; // 战利品系统的引用
    public ItemManager itemManager; // 道具管理器的引用
    public Player player;
    private bool _isOpened = false; // 用于跟踪宝箱是否已打开
    private bool _isPlayerNearby = false; // 用于跟踪玩家是否在宝箱附近
    private Transform _playerTransform; // 玩家对象的 Transform 引用
    public float interactionDistance = 4.0f; // 交互距离
    public ChestUI chestUI; // 引用 ChestUI 脚本
    public GameObject chestopen;
    public GameObject chestclose;
    void Start()
    {
        lootSystem = lootSystem ?? FindObjectOfType<LootSystem>();
        itemManager = itemManager ?? FindObjectOfType<ItemManager>();
        player = player ?? FindObjectOfType<Player>();
        _playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
        chestUI = FindObjectOfType<ChestUI>();
        
        //chestopen.SetActive(false);
        //chestclose.SetActive(true);
        
        if (lootSystem == null || itemManager == null || player == null || chestUI == null)
        {
            Debug.LogError("初始化失败，请检查依赖组件！");
        }
    }

    void Update()
    {
        float distanceToPlayer = Vector3.Distance(_playerTransform.position, transform.position);
        _isPlayerNearby = distanceToPlayer <= interactionDistance;

        if (_isPlayerNearby)
        {
            //if (!_isOpened)
                //Debug.Log("near,点击F交互");
           // else
                //Debug.Log("near");
            if (Input.GetKeyDown(KeyCode.F))
                Interact();
        }
    }

    public void Interact()
    {
        if (!_isOpened)
        {
            chestopen.SetActive(true);
            chestclose.SetActive(false);
            OpenChest();
        }
    }

    private void OpenChest()
    {
        _isOpened = true;
        Debug.Log("RewordisOpened");
        // 生成三个战利品选项
        Item[] lootOptions = new Item[3];
        for (int i = 0; i < lootOptions.Length; i++)
        {
            lootOptions[i] = lootSystem.GenerateCommonChestLoot((int)player.stats.distortionLevel);

            //lootOptions[i] = lootSystem.GenerateCommonChestLoot((int)player.stats.distortionLevel);
        }

        // 在 UI 中显示战利品选项
        chestUI.ShowLootOptions(lootOptions);

        Debug.Log("宝箱已打开，显示战利品选择界面。");
    }
}